package com.czr.handler;

import com.czr.config.mybatis.KsdConstants;
import com.czr.config.userlocal.UserThreadLcal;
import com.czr.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description:
 * Author: czr czr
 * Version: 1.0
 * Create Date Time: 2021/11/23 15:43.
 * Update Date Time:
 *
 * @see
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("1111-->执行了preHandle");
        // 如果没有登录、重定向到登录页面
        User user = (User)request.getSession().getAttribute(KsdConstants.SESSION_USER);
        if (user == null) {
            response.sendRedirect("/login");
            return false;
        }

        // 本地用户存储
        UserThreadLcal.put(user);
        //如果为false，直接阻断，不会处理任何动作，动作必须要你来决定(
        // 1:你可以选择跳转页面，(几乎用不到)
        // 2:你也重定向到你指定路由（常用做法)
        // 3:你也可以用流输出流程（常用做法)
        //如果拦截器执行完毕，返回true，代表的是:执行完毕逻辑了，去处理你springmvc的路由方法


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("3333-->执行了postHandle");
        UserThreadLcal.clear();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("4444-->执行了afterCompletion");
        UserThreadLcal.clear();
    }
}
